package pl.dmcs.grails.planner

import org.springframework.transaction.annotation.Transactional

import antlr.debug.Event

import com.dhtmlx.planner.DHXEv
import com.dhtmlx.planner.DHXEventsManager
import com.dhtmlx.planner.DHXStatus
import pl.dmcs.grails.Employee

@Transactional(readOnly = true)
class PlannerEventService extends DHXEventsManager {

    Employee employee;

    def PlannerEventService() {
    }
    
    def PlannerEventService(request, employee) {
        super(request)
        this.employee = employee
    }

    @Override
    def Iterable<PlannerEvent> getEvents() {
        return PlannerEvent.findAll(
	    "from PlannerEvent event where event.employee.id = :employeeId",
            [employeeId : this.employee.getId()]
        )
    }

    @Override
    @Transactional
    def DHXStatus saveEvent(DHXEv event, DHXStatus status) {
        def ev = (PlannerEvent) event
        if (status == DHXStatus.UPDATE) {
            ev.save();
        } else if (status == DHXStatus.DELETE) {
            ev.delete();
        } else if (status == DHXStatus.INSERT) {
            employee.addToPlannerEvents(ev);
            ev.save();
        }

        return status;
    }

    @Override
    def DHXEv createEvent(String id, DHXStatus status) {
        if (status == DHXStatus.INSERT) {
            return new PlannerEvent();
        } else {
            return PlannerEvent.get(id);
        }
    }
}
